package com.koron.css2.newProjectCenter.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.BankBean;
import com.koron.css2.baseConfig.bean.ProjectPayeeBean;
import com.koron.css2.baseConfig.mapper.*;
import com.koron.css2.baseConfig.vo.SelectVO;
import com.koron.css2.clientCenter.bean.AccountInfoBean;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.contractmanage.Enum.ContractTypeEnum;
import com.koron.css2.contractmanage.mapper.ContractManageMapper;
import com.koron.css2.contractmanage.querybean.ContractManageQueryBean;
import com.koron.css2.contractmanage.vo.ContractManageVO;
import com.koron.css2.newProjectCenter.Enum.PjInfoProcessStateEnum;
import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.bean.PjSettlement;
import com.koron.css2.newProjectCenter.bean.query.PjInfoQueryBean;
import com.koron.css2.newProjectCenter.bean.query.PjSettlementQuery;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.newProjectCenter.mapper.PjSettlementMapper;
import com.koron.css2.newProjectCenter.service.PjInfoService;
import com.koron.css2.newProjectCenter.vo.PjInfoDetailVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.DictionaryMapper;
import com.koron.css2.serviceManage.mapper.DistrictMapper;
import com.koron.css2.serviceManage.mapper.PubAdminAreaMapper;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.vo.DictionaryVO;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.bean.OrgUserQueryBean;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.*;
import java.util.stream.Collectors;


public class PjInfoQuery implements ServerInterface {

    // 是否允许修改客户信息 0 不允许 1 允许
    private static final int UPDATE_CTM_FLAG_DISABLE = 0;

    // 是否允许修改客户信息 0 不允许 1 允许
    private static final int UPDATE_CTM_FLAG_ABLE = 1;

    // 是否允许修改账户信息 0 不允许 1 允许
    private static final int UPDATE_ACCOUNT_FLAG_DISABLE = 0;

    // 是否允许修改账户信息 0 不允许 1 允许
    private static final int UPDATE_ACCOUNT_FLAG_ABLE = 1;
    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            // 1. 将入参转换为QueryBean
            PjInfoQueryBean queryBean = JsonUtils.objectToPojo(req.getData(), PjInfoQueryBean.class);
            PubAdminAreaMapper pmapper = factory.getMapper(PubAdminAreaMapper.class, "_default");
            // 2. 查询工程信息
            PjInfoMapper mapper = factory.getMapper(PjInfoMapper.class);
            PjInfoBean pjInfoBean = mapper.getSingle(queryBean);
            if (pjInfoBean == null) {
                return MessageBean.create(Constant.NOT_NULL, "工程单据不存在。", null);
            }
            // 2.1 兼容草稿数据
            if (StringUtils.isEmpty(pjInfoBean.getProcessState())) {
                pjInfoBean.setProcessState(PjInfoService.REGISTER);
            }
            ContractManageMapper contractManageMapper = factory.getMapper(ContractManageMapper.class);
            //施工合同
            ContractManageQueryBean contractManageQueryBean = new ContractManageQueryBean();
            contractManageQueryBean.setContractTypes(new String[]{ContractTypeEnum.CONTRACT_TYPE_4.getContractType(),ContractTypeEnum.CONTRACT_TYPE_5.getContractType()});
            contractManageQueryBean.setProjectId(pjInfoBean.getId());
            ContractManageVO contractManage=new ContractManageVO();
            ContractManageVO gscontractManageVO = contractManageMapper.getContractManage(contractManageQueryBean);
            if (ObjectUtil.isNotNull(gscontractManageVO)){
                BeanUtil.copyProperties(gscontractManageVO,contractManage);
            }
            if (StringUtils.isNotEmpty(pjInfoBean.getContractNo())){
                contractManage.setContractNo(pjInfoBean.getContractNo());
            }

            // 是否允许修改客户信息 0 不允许 1 允许
            Integer updateCtmFlag = UPDATE_CTM_FLAG_DISABLE;
            if (Objects.equals(pjInfoBean.getProcessState(), PjInfoProcessStateEnum.REGISTER.getProcessState())) {
                updateCtmFlag = UPDATE_CTM_FLAG_ABLE;
            }
            // 是否允许修改账户信息 0 不允许 1 允许
            Integer updateAccountFlag = UPDATE_ACCOUNT_FLAG_DISABLE;
            if (Objects.equals(pjInfoBean.getProcessState(), PjInfoProcessStateEnum.REGISTER.getProcessState())) {
                updateAccountFlag = UPDATE_ACCOUNT_FLAG_ABLE;
            }
            // 3. 查询客户信息
            CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
            CtmInfoBean ctmInfoBean = ctmMapper.getCtmInfoById(pjInfoBean.getUserCtmTempId(), 2);
            String clientAddr = ctmInfoBean.getClientAddr();
            if (!StringUtils.isEmpty(clientAddr)) {
                ctmInfoBean.setClientAddrId(clientAddr);
                String area = pmapper.selectFullNameById(clientAddr);
                ctmInfoBean.setClientAddr(area);
            }
            // 5. 查询账户信息
            AccountInfoMapper accountMapper = factory.getMapper(AccountInfoMapper.class);
            AccountInfoBean accountInfoBean = accountMapper.getAccountInfoById(pjInfoBean.getUserAccountTempId(), 2);
            if (accountInfoBean == null) {
                accountInfoBean = new AccountInfoBean();
            }
            // 7. 根据业务节点将只读字段进行数据字典转换
            convertStatus(factory, pjInfoBean, ctmInfoBean, accountInfoBean, userInfo);
            Map<String, String> IDT = Tools.mapDicByCode(factory, "IDT");
            Map<String, String> PCW = Tools.mapDicByCode(factory, "PCW");//结算方式
            if (!StringUtils.isBlank(pjInfoBean.getAgentCertType())) {
                pjInfoBean.setAgentCertTypeName(IDT.get(pjInfoBean.getAgentCertType()));
            }
            if (!StringUtils.isBlank(pjInfoBean.getPrepayType())) {
                pjInfoBean.setPrepayTypeName(PCW.get(pjInfoBean.getPrepayType()));
            }
            if (pjInfoBean.getDepositMoney() == null) {
                pjInfoBean.setDepositMoney(0.0);
            }
            // 8. 转化岗位人员名称
            OrgUserMapper omapper = factory.getMapper(OrgUserMapper.class);
            if (!StringUtils.isBlank(pjInfoBean.getInstallStaff())) {
                OrgUserQueryBean orgUserQueryBean = new OrgUserQueryBean();
                orgUserQueryBean.setUserAccounts(Arrays.asList(pjInfoBean.getInstallStaff().split(",")));
                List<OrgUserBean> olist = omapper.selectByAccounts(orgUserQueryBean);
                if (olist != null && olist.size() > 0) {
                    List<String> installStaffName = new ArrayList<String>();
                    for (int i = 0; i < olist.size(); i++) {
                        installStaffName.add(olist.get(i).getUserName());
                    }
                    pjInfoBean.setInstallStaffName(String.join(",", installStaffName));
                }
            }
            // 9. 施工人员
            if (!StringUtils.isBlank(pjInfoBean.getConstGroup())) {
                OrgUserQueryBean orgUserQueryBean = new OrgUserQueryBean();
                orgUserQueryBean.setUserAccounts(Arrays.asList(pjInfoBean.getConstGroup().split(",")));
                List<OrgUserBean> olist = omapper.selectByAccounts(orgUserQueryBean);
                if (olist != null && olist.size() > 0) {
                    List<String> constGroupName = new ArrayList<String>();
                    for (int i = 0; i < olist.size(); i++) {
                        constGroupName.add(olist.get(i).getUserName());
                    }
                    pjInfoBean.setConstGroupName(String.join(",", constGroupName));
                }
            }
            // 10. 勘察人员
            if (!StringUtils.isBlank(pjInfoBean.getSurveyStaff())) {
                // 2022.1.7: 勘察邀约支持选择多人
                String userListString = pjInfoBean.getSurveyStaff();
                List<String> userList = Arrays.asList(userListString.split(","));
                List<String> userNameList = omapper.getUserNameListByAccounts(userList);
                String userNameString = userNameList.stream().collect(Collectors.joining(","));
                pjInfoBean.setSurveyStaffName(userNameString);
            }
            // 11. 设计人员
            if (!StringUtils.isBlank(pjInfoBean.getDesignStaff())) {
                OrgUserBean user = omapper.selectByAccount(pjInfoBean.getDesignStaff());
                pjInfoBean.setDesignStaffName(user == null ? "" : user.getUserName());
            }
            // 12. 预算编制人员
            if (!StringUtils.isBlank(pjInfoBean.getBudgetStaff())) {
                OrgUserBean user = omapper.selectByAccount(pjInfoBean.getBudgetStaff());
                pjInfoBean.setBudgetStaffName(user == null ? "" : user.getUserName());
            }
            // 13. budgetPayStaff
            if (!StringUtils.isBlank(pjInfoBean.getBudgetPayStaff())) {
                OrgUserBean user = omapper.selectByAccount(pjInfoBean.getBudgetPayStaff());
                pjInfoBean.setBudgetPayStaffName(user == null ? "" : user.getUserName());
            }
            String checkInviteStaffName = "";
            if (StringUtils.isNotEmpty(pjInfoBean.getCheckInviteStaff())) {
                String[] checkInviteStaffList = pjInfoBean.getCheckInviteStaff().split(",");
                for (String singleStaff : checkInviteStaffList) {
                    OrgUserBean orgUserBean = omapper.selectByAccount(singleStaff);
                    if (orgUserBean != null) {
                        checkInviteStaffName += orgUserBean.getUserName() + ',';
                    }
                }
                if(StringUtils.isNotBlank(checkInviteStaffName)){
                    checkInviteStaffName = checkInviteStaffName.substring(0, checkInviteStaffName.length() - 1);
                }
                // 验收邀约人员名称
                pjInfoBean.setCheckInviteStaffName(checkInviteStaffName);
            }
            // 是否红线内施工
            Integer redLineConstruction = pjInfoBean.getRedLineConstruction();
            if (redLineConstruction != null && redLineConstruction == 1) {
                pjInfoBean.setRedLineConstructionName("需要");
            }
            if (redLineConstruction != null && redLineConstruction == 0) {
                pjInfoBean.setRedLineConstructionName("不需要");
            }
            PjSettlementQuery pjSettlementQuery = new PjSettlementQuery();
            pjSettlementQuery.setConsultId(pjInfoBean.getId());
            PjSettlementMapper pjSettlementMapper = factory.getMapper(PjSettlementMapper.class);
            PjSettlement pjSettlement = pjSettlementMapper.getSingle(pjSettlementQuery);

            // 16. 输出VO组装selectByAccount
            PjInfoDetailVO detailVO = new PjInfoDetailVO();
            pjInfoBean.setPrepayMoney((pjInfoBean.getBudgetMoney() == null ? 0.0 : pjInfoBean.getBudgetMoney()) + (pjInfoBean.getDepositMoney() == null ? 0.0 : pjInfoBean.getDepositMoney()));
            pjInfoBean.setConstructionDesignCost((pjInfoBean.getUnitDesignCost()== null ? 0.0 :pjInfoBean.getUnitDesignCost())+ (pjInfoBean.getOutsideRedLineEditCost()== null ? 0.0 :pjInfoBean.getOutsideRedLineEditCost())+ (pjInfoBean.getInsideRedLineEditCost()== null ? 0.0 :pjInfoBean.getInsideRedLineEditCost())  );
            detailVO.setConsult(pjInfoBean);
            detailVO.setCtmInfo(ctmInfoBean);
            detailVO.setAccountInfo(accountInfoBean);
            detailVO.setUpdateCtmFlag(updateCtmFlag);
            detailVO.setUpdateAccountFlag(updateAccountFlag);
            detailVO.setPjSettlement(pjSettlement);
            detailVO.setApproveFlag(0);
            detailVO.setSgContract(contractManage);
            if (
                    !StringUtils.isBlank(pjInfoBean.getProcessState()) && ("CANCEL".equals(pjInfoBean.getProcessState())
                    || "END".equals(pjInfoBean.getProcessState())
                    || isApproval(pjInfoBean.getProcessState()))) {
                detailVO.setApproveFlag(1);
            }
            MessageBean<PjInfoDetailVO> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PjInfoDetailVO.class);
            info.setData(detailVO);
            return info;
        } catch (Exception e) {
            logger.error("工程详情查询失败" + e.getMessage(), e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
        }
    }

    /**
     * 判断流程状态
     */
    public boolean isApproval(String process) {
        if (!StringUtils.equalsAny(process, PjInfoService.REGISTER, PjInfoService.REGISTER_APPROVAL, PjInfoService.INFO_APPROVAL,
                PjInfoService.INVITATION_SURVEY, PjInfoService.SURVEY, PjInfoService.DESIGN, PjInfoService.DESIGN_APPROVAL,
                PjInfoService.BUDGET, PjInfoService.BUDGET_APPROVAL, PjInfoService.BUILD, PjInfoService.INSTALL_BUILD,
                PjInfoService.REGISTER_ACCOUNT, PjInfoService.REGISTER_ACCOUNT_APPROVAL, PjInfoService.INVITATION_CHECK,
                PjInfoService.INVITATION_CHECK_ACCEPT, PjInfoService.CHECK, PjInfoService.METER_HOOK, PjInfoService.DATA_ARCHIVE,
                PjInfoService.PJSETTLEMENT, PjInfoService.PJPAYMENT, PjInfoService.PAYMENT, PjInfoService.CHECK_PROCEDURES
                )) {
            return true;
        }else {
            return false;
        }
    }

    /**
     * 字段转换
     *
     * @param factory
     * @param ctmInfoBean
     * @param accountInfoBean
     */
    public void convertStatus(SessionFactory factory, PjInfoBean pjInfoBean,
                              CtmInfoBean ctmInfoBean, AccountInfoBean accountInfoBean, UserInfoBean userInfo) {
        DictionaryMapper dictionaryMapper = factory.getMapper(DictionaryMapper.class);
        String codes[] = "CTT,IDT,CDL,PPT,EGD,ACT,BBT,SDW,PIS,UWD,BPW,PJC,BPP".split(",");
        List<DictionaryVO> list = dictionaryMapper.findDictionaryByCodes(codes);
        //预算节点
        BankMapper bankeMapper = factory.getMapper(BankMapper.class);
        BusinessAbodeMapper Businessmapper = factory.getMapper(BusinessAbodeMapper.class, "_default");
        for (DictionaryVO d : list) {
            if (ctmInfoBean.getCtmType() != null && "CTT".equals(d.getCode()) && ctmInfoBean.getCtmType().equals(d.getValue())) {
                //客户类型
                ctmInfoBean.setCtmTypeName(d.getName());
            } else if (ctmInfoBean.getCertType() != null && "IDT".equals(d.getCode()) && ctmInfoBean.getCertType().equals(d.getValue())) {
                //证件类型
                ctmInfoBean.setCertTypeName(d.getName());
            } else if (ctmInfoBean.getCreditLevel() != null && "CDL".equals(d.getCode()) && ctmInfoBean.getCreditLevel().equals(d.getValue())) {
                //信用级别
                ctmInfoBean.setCreditLevelName(d.getName());
            } else if (pjInfoBean.getPjType() != null && "PPT".equals(d.getCode()) && pjInfoBean.getPjType().equals(d.getValue())) {
                //工程类型
                pjInfoBean.setPjTypeName(d.getName());
            } else if (pjInfoBean.getUrgentFlag() != null && "EGD".equals(d.getCode()) && pjInfoBean.getUrgentFlag().equals(d.getValue())) {
                //紧急程度
                pjInfoBean.setUrgentFlagName(d.getName());
            } else if (accountInfoBean.getAccountType() != null && "ACT".equals(d.getCode()) && accountInfoBean.getAccountType().equals(d.getValue())) {
                //账户类型
                accountInfoBean.setAccountTypeName(d.getName());
            } else if (accountInfoBean.getInvoiceType() != null && "BBT".equals(d.getCode()) && accountInfoBean.getInvoiceType().equals(d.getValue())) {
                //发票类型
                accountInfoBean.setInvoiceTypeName(d.getName());
            } else if (accountInfoBean.getDeliverWay() != null && "SDW".equals(d.getCode()) && accountInfoBean.getDeliverWay().equals(d.getValue())) {
                //投递方式
                accountInfoBean.setDeliverWayName(d.getName());
            } else if (pjInfoBean.getSourceFlag() != null && "PIS".equals(d.getCode()) && pjInfoBean.getSourceFlag().equals(d.getValue())) {
                //信息来源
                pjInfoBean.setSourceFlagName(d.getName());
            } else if (pjInfoBean.getLimitFlag() != null && "UWD".equals(d.getCode()) && pjInfoBean.getLimitFlag().equals(d.getValue())) {
                //用水期
                pjInfoBean.setLimitFlagName(d.getName());
            } else if (accountInfoBean.getPayWay() != null && "BPW".equals(d.getCode()) && accountInfoBean.getPayWay().equals(d.getValue())) {
                //缴费方式
                accountInfoBean.setPayWayName(d.getName());
            } else if (pjInfoBean.getBudgetPayWay() != null && "BPP".equals(d.getCode()) && pjInfoBean.getBudgetPayWay().toString().equals(d.getValue())) {
                //预缴方式
                pjInfoBean.setBudgetPayWayName(d.getName());
            }
        }
        if (StringUtils.isNotBlank(accountInfoBean.getVatFlag()) && "1".equals(accountInfoBean.getVatFlag())) {
            accountInfoBean.setVatFlagName("是");
        } else {
            accountInfoBean.setVatFlagName("否");
        }
        if (!StringUtils.isBlank(pjInfoBean.getMeterBore())) {
            pjInfoBean.setMeterBoreName(factory.getMapper(MeterBoreMapper.class).selectMeterBoreById(pjInfoBean.getMeterBore()).getBoreName());
        }
        if (pjInfoBean.getProjectCharge() != null) {
            //收款主体
            ProjectPayeeBean bean = new ProjectPayeeBean();
            bean.setId(pjInfoBean.getProjectCharge());
            ProjectPayeeMapper mapper = factory.getMapper(ProjectPayeeMapper.class);
            ProjectPayeeBean rojectPayeeBean = mapper.query(bean);
            pjInfoBean.setProjectChargeName(rojectPayeeBean != null ? rojectPayeeBean.getSubjectName() : "");
        }
        //开户行
        if (!StringUtils.isBlank(accountInfoBean.getOpenAccountBank())) {
            BankMapper bankMapper = factory.getMapper(BankMapper.class);
            BankBean bankBean = bankMapper.findBankById(accountInfoBean.getOpenAccountBank());
            accountInfoBean.setOpenAccountBankName(bankBean.getBankName());
        }
        // 获取购买方开户行名称
        if (!StringUtils.isBlank(accountInfoBean.getInvoiceBank())) {
            BankBean bankName = bankeMapper.findBankById(accountInfoBean.getInvoiceBank());
            accountInfoBean.setInvoiceBankName(bankName == null ? "" : bankName.getBankName());
        }
        // 获取行政区域
        if (!StringUtils.isEmpty(pjInfoBean.getAdminArea())) {
            DistrictMapper districtMapper = factory.getMapper(DistrictMapper.class);
            pjInfoBean.setAdminAreaName(districtMapper.findDistrictById(pjInfoBean.getAdminArea()).getSname());
        }
        // 获取营业区域
        if (!StringUtils.isEmpty(pjInfoBean.getBusinessArea())) {
            BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
            pjInfoBean.setBusinessAreaName(
                    businessAreaMapper.findBusinessAreaById(pjInfoBean.getBusinessArea(), userInfo.getCurWaterCode()));
        }
        //营业所
        //获取下拉框
        List<SelectVO> blist = Businessmapper.businessAbodeSelect(userInfo.getCurWaterCode());
        for (SelectVO selectVO : blist) {
            if (pjInfoBean.getBusinessAbode() != null && selectVO.getId().equals(pjInfoBean.getBusinessAbode())) {
                pjInfoBean.setBusinessAbodeName(selectVO.getName());
            }
        }

    }
}
